package com.fire.mongo.api.daos;

import java.util.ArrayList;
import java.util.List;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * @date 2022/4/21
 * @author zwd
 * @email zwd@hhh.com
 */
public class MovieDao extends AbstractMFlixDao{
	public static String MOVIES_COLLECTION = "movies";

	private MongoCollection<Document> moviesCollection;

	@Autowired
	protected MovieDao(MongoClient mongoClient, @Value("${spring.mongodb.database}") String databaseName) {
		super(mongoClient, databaseName);
		moviesCollection = db.getCollection(MOVIES_COLLECTION);
	}

	@SuppressWarnings("unchecked")
	private Bson buildLookupStage() {
		return null;
	}

	/**
	 * movieID 需要是一个 16 进制的字符串，否则它将不会被转化为一个 ObjectID
	 * @param movieId
	 * @return
	 */
	private boolean validIdValue(String movieId){
		//TODO> Ticket: Handling Errors - implement a way to catch a
		return true;
	}

	/**
	 * 从数据库中获取movie
	 * @param movieId
	 * @return
	 */
	@SuppressWarnings("UnnecessaryLocalVariable")
	public Document getMovie(String movieId){
		if (movieId == null) {
			return null;
		}

		ArrayList<Bson> pipeline = new ArrayList<>();
		Bson match = Aggregates.match(Filters.eq("_id", new ObjectId(movieId)));
		pipeline.add(match);

		// TODO> Ticket: Get Comments - implement the lookup stage that allows the comments to
		// retrieved with Movies.
		Document movie = moviesCollection.aggregate(pipeline).first();
		return movie;
	}

	/**
	 * 返回所有与之匹配的电影
	 * @param country
	 * @return
	 */
	public List<Document> getMoviesByCountry(String... country){
		Bson queryFilter = Filters.in("countries", country);
		Bson projection = Projections.include("title");
		List<Document> movies = new ArrayList<>();
		moviesCollection
				.find(queryFilter)
				.projection(projection)
				.iterator()
				.forEachRemaining(movies::add);
		return movies;
	}
}
